/*
 * Copyright (C) 2012 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package com.example.google.tv.picasanotifier;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.google.tv.picasanotifier.model.PicasaUrl;
import com.example.google.tv.picasanotifier.model.UserFeed;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;

import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * The activity allows the user to follow any picasa accounts which has public
 * albums.User should be able to enter the username/email whom they want to
 * follow .Clicking any user will launch the AlbumActivity.
 */

public class MainActivity extends Activity implements android.view.View.OnClickListener {
    private ArrayAdapter<String> mAdapter;

    private Button mAddButton;

    private ListView mListView;

    private EditText mEdittext;

    /**
     * Database class that stores all the Picasa contacts
     */
    private UserDatabase mUserDb;

    private UserFeed mUserFeed;

    private Cursor mCursor;

    private String[] mUsers;

    private PendingIntent mAlarmSender;

    /**
     * Utility class to interact with Picasa API and returns the unique instance
     * of the class
     */
    final Picasa mPicasa = Picasa.get();

    /**
     * Setup the HttpTransport to build the Picasa url
     */
    private HttpTransport mTransport = mPicasa.picasaInit();

    RelativeLayout mLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mAlarmSender = PendingIntent.getService(MainActivity.this, 0, new Intent(MainActivity.this,
                CheckUpdateService.class), 0);
        mAddButton = (Button)findViewById(R.id.add_button);
        mListView = (ListView)findViewById(R.id.list_view);
        mEdittext = (EditText)findViewById(R.id.user_name);
        mUserDb = new UserDatabase(this);
        mUserDb.open();
        setListAdapter();
        populateUsers();
        mAddButton.setOnClickListener(this);
        mListView.setOnItemClickListener(mListListener);
        registerForContextMenu(mListView);

        mEdittext.setOnKeyListener(new android.view.View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
                    if (event.getAction() == KeyEvent.ACTION_UP) {
                        checkUser();
                        return true;
                    }
                }
                return false;
            }
        });
        scheduleAlarmFirsttime();
        mUserDb.close();
    }

    /**
     * Initialize the list adapter to show the list of following users
     */
    public void setListAdapter() {
        mAdapter = new ArrayAdapter<String>(this, R.layout.user_list);
        mUsers = getResources().getStringArray(R.array.usernames);
        for (String item : mUsers) {
            mAdapter.add(item);
        }
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, 0, 0, getText(R.string.delete));
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        switch (item.getItemId()) {
            case 0:
                // Delete the account if the user doesn't want to follow
                // their account
                mUserDb.open();
                mUserDb.deleteName(mListView.getItemAtPosition(info.position).toString());
                mUserDb.close();
                mAdapter.remove(mListView.getItemAtPosition(info.position).toString());
                mAdapter.notifyDataSetChanged();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * Schedule the alarm
     */
    private void scheduleAlarmFirsttime() {
        long firstTime = SystemClock.elapsedRealtime();
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30 * 1000, mAlarmSender);
        CheckUpdateService.scheduleAlarm(this);
    }

    /**
     * Populate the users from database and display them in list adapter
     */
    public void populateUsers() {
        mCursor = mUserDb.getAllNames();
        if (mCursor != null) {
            if (mCursor.moveToFirst()) {
                do {
                    String item = mCursor.getString(1);
                    if (!item.equals("")) {
                        mAdapter.add(item);
                    }
                } while (mCursor.moveToNext());
            }
        }
    }

    private OnItemClickListener mListListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
            Intent intent = new Intent(MainActivity.this, AlbumActivity.class);
            intent.putExtra("username", mListView.getItemAtPosition(pos).toString());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    };

    /**
     * Check whether the user is already in the following list or not. Add the
     * new user if doesn't exists in the current list.
     */
    public void checkUser() {
        final String mUsername = mEdittext.getText().toString();
        mEdittext.setText("");
        if (!mUsername.equals("")) {
            PicasaUrl url = PicasaUrl.fromRelativePath(Picasa.API_FEED_URL + mUsername);
            try {
                mUserFeed = UserFeed.executeGet(mTransport, url);
                if (mUserFeed != null) {
                    mUserDb.open();
                    if (!checkName(mUsername)) {
                        mUserDb.insertName(mUsername, "abc", 1, (int)System.currentTimeMillis());
                        mUserDb.close();
                        mAdapter.add(mUsername);
                    } else {
                        Toast toast = Toast.makeText(getApplicationContext(),
                                getText(R.string.user_exist), Toast.LENGTH_LONG);
                        toast.show();
                    }
                }
            } catch (IOException e) {
                showWarningToast(e);
            }
        }
    }

    @Override
    public void onClick(View v) {
        checkUser();
    }

    /**
     * Check for duplicate names
     * 
     * @param username The given username
     * @return True if the user already exists in the list.False otherwise.
     */
    private boolean checkName(String username) {
        for (int i = 0; i < mAdapter.getCount(); i++) {
            if (mAdapter.getItem(i).equals(username)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Show toast if there is no public albums
     * 
     * @param e Exception if there is no public albums
     */
    private void showWarningToast(Exception e) {
        int statusCode = ((HttpResponseException)e).response.statusCode;
        if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
            Toast toast = Toast.makeText(getApplicationContext(), getText(R.string.no_album),
                    Toast.LENGTH_LONG);
            toast.show();
        }
    }
}
